import { reqGetCode } from "@/api"
import { reqUserRegister } from "@/api"
import { reqUserLogin, reqUserInfo, reqLogOut } from '@/api'
import { setToken, removeToken } from '@/utils/token'
//登录与注册的模块
const state = {
    code: '',
    token: localStorage.getItem("TOKEN"),
    userInfo: {},
}
const mutations = {
    GETCODE(state, code) {
        state.code = code
    },
    USERLOGIN(state, token) {
        state.token = token
    },
    GETUSERINFO(state, userInfo) {
        state.userInfo = userInfo
    },
    //清除本地user数据
    CLEAR(state) {
        //vuex把仓库中的数据清空
        state.token = '',
            state.userInfo = {},
            //本地储存清空 
            removeToken()
    }
}
const actions = {
    //获取验证码
    async getCode({ commit }, phone) {
        //获取验证码的接口直接把验证码返回了，但是正常情况应该是后台将验证码发给手机
        let result = await reqGetCode(phone)
        if (result.code == 200) {
            commit('GETCODE', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //用户注册
    async userRegister({ commit }, user) {
        let result = await reqUserRegister(user)
        //此处不需要三连环了，他没有返回的数据
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //用户登录【token】
    async userLogin({ commit }, data) {
        let result = await reqUserLogin(data)
        //服务器下发的token，是用户的唯一标识
        //将来经常通过带token找服务器要用户的信息进行展示
        if (result.code == 200) {
            //用户已经登录成功且获取到token
            commit("USERLOGIN", result.data.token)
            //需要持久化储存token
            setToken(result.data.token)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }

    },
    //获取用户信息
    async getUserInfo({ commit }) {
        let result = await reqUserInfo()
        if (result.code == 200) {
            commit('GETUSERINFO', result.data)
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    //退出登录
    async userLogOut({ commit }) {
        //只是向服务器发出一次请求，通知服务器清除服务器的token
        let result = await reqLogOut()
        //这里开始清除本地的user数据
        if (result.code == 200) {
            //actions中不能操作state,必须先提交mutation
            commit("CLEAR")
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    }
}
const getters = {

}
export default {
    state, mutations, actions, getters
}